package com.maruping.disk.login.control;

import com.maruping.disk.login.entity.MenuLevelEntity;
import com.maruping.disk.login.service.LoginService;
import com.maruping.disk.mybatis.entity.PtUserEntity;
import com.maruping.disk.spring.security.UserDiskEntity;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class MainController {
    @Resource
    private HttpSession httpSession;

    @Resource
    private LoginService loginService;

    @RequestMapping("/")
    public String main(HttpSession session, RedirectAttributes redirectAttributes) {
        UserDiskEntity userDiskEntity = (UserDiskEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        session.setAttribute("userUuidDisk", userDiskEntity.getUserUuid());
        session.setAttribute("lang", LocaleContextHolder.getLocale().toString());
        List<MenuLevelEntity> list = loginService.queryMenuListLevel();
        session.setAttribute("menuList", list);

        // 检查密码是否为空，如果为空，重定向到修改密码页面
        PtUserEntity user = loginService.queryUserInfoByName(userDiskEntity.getUsername());
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            redirectAttributes.addFlashAttribute("mustChangePassword", true);
            return "redirect:/user/changePassword";
        }

        return "login/mainPage";
    }

    @RequestMapping("/welcomePage")
    public String queryMenuListLevel(){
        return "login/welcomePage";
    }

    @Secured("ROLE_Test1")
    @RequestMapping("/test1")
    public String test1(){
        return "test/test1Page";
    }

    @Secured("ROLE_Test2")
    @RequestMapping("/test2")
    public String test2(){
        return "test/test2Page";
    }
}